package com.dlshouwen.wzgl.baseinfo.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dlshouwen.core.base.config.CONFIG;
import com.dlshouwen.core.base.model.AjaxResponse;
import com.dlshouwen.core.base.utils.UpDownLoadUtils;
import com.dlshouwen.wzgl.baseinfo.dao.BaseInfoDao;
import com.dlshouwen.wzgl.baseinfo.model.BaseInfo;

@Controller
@RequestMapping("/wzgl/baseInfo")
public class BaseInfoController {
	//根路径
    private String basePath = "wzgl/baseInfo/";
    
    private BaseInfoDao dao;

    //注入dao
    @Resource(name = "baseInfoDao")
	public void setDao(BaseInfoDao dao) {
		this.dao = dao;
	}
    
    //跳转到网站信息页面
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String goBaseInfoPage(HttpServletRequest request, Model model) throws Exception {
    	BaseInfo baseInfo = dao.select();
    	model.addAttribute("baseInfo", baseInfo);
    	
        //跳转网站信息页面
        return basePath + "detail";
    }
    
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse edit(HttpServletRequest request, BaseInfo baseInfo) {
//		定义AJAX响应回执
        AjaxResponse ajaxResponse = new AjaxResponse();
        try {
        	String path = null;
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("piclogo");
            if(null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) {
            	path = UpDownLoadUtils.uploadFile(multipartFile, CONFIG.SOURCE_REAL_PATH, CONFIG.UPLOAD_PIC_PATH);
            }
        	baseInfo.setLogo(path);
        	dao.update(baseInfo);
        } catch(Exception e) {
        	e.printStackTrace();
        	ajaxResponse.setError(true);
        	ajaxResponse.setErrorMessage("保存失败，后台程序出错！");
            return ajaxResponse;
        }
        ajaxResponse.setSuccess(true);
        ajaxResponse.setSuccessMessage("保存成功！");
        ajaxResponse.setData(baseInfo);
        return ajaxResponse;
    }
}
